package run;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;

import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

import linker.CONFIGSQL;

import util.CONFIG;
import dto.ConfigServidorDTO;
import dto.ExecStepDTO;
import dto.SalidaDTO;
import executor.ProcExecutor;

public class Modulo {

	public String nombre;
	public String ubicacion;
	public HashMap<String, ConfigServidorDTO> servidores;
	public ArrayList<SalidaDTO> salidas;
	
	public Modulo() {
		servidores = new HashMap<String, ConfigServidorDTO>();
		salidas = new ArrayList<SalidaDTO>();
	}

	public int run(ExecStepDTO step) {
		printXML(step);
		return execute(step);
	}

	private void printXML(ExecStepDTO step) {
		XMLOutputFactory output = XMLOutputFactory.newInstance();
		XMLStreamWriter writer = null;
	
		ConfigServidorDTO auxServ = servidores.get(step.servidor);
		try {
			writer = output.createXMLStreamWriter(new FileWriter(ubicacion.replace(".jar",".xml")));
			writer.writeStartDocument();
			writer.writeStartElement(nombre);
			writer.writeStartElement("fecha");
			writer.writeCharacters(step.fecha.getFecha());
			writer.writeEndElement();
			writer.writeStartElement("servidor");
			writer.writeCharacters(step.servidor);
			writer.writeEndElement();
			writer.writeStartElement("ubicacion");
			writer.writeCharacters(auxServ.pathOrigen);
			writer.writeEndElement();
			writer.writeStartElement("destino");
			writer.writeCharacters(CONFIG.getPathArchivos());
			writer.writeEndElement();
			for (Entry<String, String> aux : auxServ.parametros.entrySet()) {
				writer.writeStartElement(aux.getKey());
				writer.writeCharacters(aux.getValue());
				writer.writeEndElement();
			}
			writer.writeEndElement();
			writer.writeEndDocument();
			writer.flush();
			writer.close();
		} catch (XMLStreamException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private int execute(ExecStepDTO step) {
		String aux = "java -jar " + ubicacion;
		ProcExecutor executor = new ProcExecutor();
		int result = -1;
		if (executor.runCMD(aux) == 0)
			result = upload(step);
		return result;
	}

	private int upload(ExecStepDTO step) {
		int result = 0;
		for (SalidaDTO dto : salidas) {
			String aux = CONFIGSQL.getBCPParams(dto);
			ProcExecutor executor = new ProcExecutor();
			result += executor.runCMD(aux);
		}
		return result;
	}
}